package com.wlq.http;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;


public class HttpRequest {

    private String method;//请求方式
    private String uri;//抽象路径
    private String protocol;//协议版本

    private Map<String,String> headers = new HashMap<>();//保存所有消息头



    private Socket socket;

    public HttpRequest(Socket socket){
        try {
            this.socket = socket;
            parseRequestLine();
            parseHeaders();
            parseContent();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void parseRequestLine() throws IOException {
        String line = readLine();
        System.out.println(line);
        String[] data = line.split("\\s");
        method = data[0];
        uri = data[1];
        protocol = data[2];
        System.out.println("method:"+method);
        System.out.println("uri:"+uri);
        System.out.println("protocol:"+protocol);
    }

    /**
     * 请求头
     * @throws IOException
     */
    private void parseHeaders() throws IOException {
        while(true) {
            String line = readLine();
            if(line.isEmpty()){
                break;
            }
            System.out.println("消息头:" + line);
            //将消息头按照": "拆分,将名字作为key,值作为value存入headers
            String[] arr = line.split(":\\s");
            headers.put(arr[0],arr[1]);
        }
        System.out.println("headers:"+headers);
    }

    /**
     * 解析请求体
     */
    private void parseContent(){}

    /**
     * 解释http请求的一行
     * @return
     * @throws IOException
     */
    private String readLine()throws IOException{
        StringBuilder builder = new StringBuilder();
        InputStream in = socket.getInputStream();
        int d;
        char pre='a',cur='a';
        while((d = in.read()) != -1){
            cur = (char)d;
            if(pre == 13 && cur == 10){
                break;
            }
            builder.append(cur);
            pre = cur;
        }
        return builder.toString().trim();//trim的目的是去除最后的回车符
    }

    public String getMethod() {
        return method;
    }


    public String getUri() {
        return uri;
    }

    public String getProtocol() {
        return protocol;
    }


    public String getHeader(String name){
        return headers.get(name);
    }

}
